package com.nulldev.util.java.swing;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class SizeFilter extends DocumentFilter {

    private int maxCharacters;
    public SizeFilter(int maxChars) {
        maxCharacters = maxChars;
    }

    public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) 
        throws BadLocationException {
        if ((fb.getDocument().getLength() + str.length()) > maxCharacters) {
            int trim = maxCharacters - (fb.getDocument().getLength() + str.length()); //trim only those characters we need to
            fb.remove(0, trim);
        }
        super.insertString(fb, offs, str, a);
    }

    public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) 
        throws BadLocationException {

        if ((fb.getDocument().getLength() + str.length() - length) > maxCharacters) {
            int trim = maxCharacters - (fb.getDocument().getLength() + str.length() - length); // trim only those characters we need to
            fb.remove(0, trim);
        }
        super.replace(fb, offs, length, str, a);
    }
}
